package com.time.service.impl;

import com.time.entity.LoginUser;
import com.time.entity.User;
import com.time.service.LoginService;
import com.time.utils.JwtUtil;
import com.time.utils.RedisCache;
import com.time.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author mjw
 * @date 2022/11/29
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResultVO login(User user) {
        //3使用ProviderManager auth方法进行验证
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果校验失败了
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误！");
        }

        //生成jwt给前端
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        // 用户的所有信息都放入redis

        // TODO 如果token未过期，一直获取当前的token
        // 套一层方法，获取token，否则如果使用以前的token，也能直接删除redis，从而实现退出
        redisCache.setCacheObject("login:" + userId, loginUser);
        return new ResultVO(200, "登陆成功", map);
    }

    @Override
    public ResultVO logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userId);
        return new ResultVO(200, "退出成功！", loginUser);
    }
}
